package com.woniu.service.Impl.homePage;

import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.dao.homePage.UsersInfoDao;
import com.woniu.entity.Users;
import com.woniu.dao.homePage.UsersDao;
import com.woniu.entity.UsersInfo;
import com.woniu.entity.WorkUser;
import com.woniu.service.homePage.IUsersService;
import com.woniu.util.RegexUtils;
import com.woniu.util.RequestParams;
import com.woniu.util.ResData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/*
 * 用户登录实现层
 * @Author 李松桦
 * @since 2023-03-02*/
@Slf4j
@Service
public class UsersServiceImpl implements IUsersService {
    @Autowired
    UsersDao usersMapper;
    @Autowired
    UsersInfoDao usersInfoDao;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /*通过手机号发送短信验证码
     * */
    @Override
    public ResData<?> SendCode(String phone) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)){
            //2.如果不符合，返回手机号格式错误
            return new ResData<>().ok("手机号格式错误");
        }
        //3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.保存验证码到redis
        redisTemplate.opsForValue().set("phoneCode:"+phone,code,60, TimeUnit.SECONDS);
        //5.发送验证码
        log.debug("发送短信验证码成功，验证码：{}",code);
        System.out.println("发送短信验证码成功，验证码："+code);
        //返回ok
        return new ResData<>().ok();
    }

    /*
     * 手机用户端 通过手机号注册登录*/
    @Override
    public ResData<?> UsersLoginRegister(String phone, String code) {
        String usersPhone = redisTemplate.opsForValue().get("userPhone:" + phone);
        String codeRedis = redisTemplate.opsForValue().get("phoneCode:"+phone);

        //判断redis是否有该用户
        if (usersPhone != null){
            //返回登录成功
            return ResData.LOGIN_SUCCESS;
        }
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
           //2.如果不符合，返回手机号格式错误
           return new ResData<>().fail();
       }
        //3.去数据库查询该手机号是否已注册
        Users users = usersMapper.UsersLoginPhone(phone);


             if (users == null  && code.equals(codeRedis)) {
                //4.未注册，给该手机号自动注册
                usersMapper.insertUsers(phone);
                UsersInfo usersInfo = new UsersInfo();
                usersInfo.setPhone(phone);
                //把字符串存到昵称字段
                usersInfo.setNickname("user_"+RandomUtil.randomString(10));
                //给所有新用户一个默认的头像
                usersInfo.setIcon("https://img2.baidu.com/it/u=1409907170,1333804870&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200");
                /*用户注册时，添加用户个人资料,手机号为前端传过来的手机号
                 * 头像设置默认头像, 昵称随机生成八位字符串*/
                usersInfoDao.insertUserInfo(usersInfo);
                 //把用户手机号作为凭证存到redis里面
                 redisTemplate.opsForValue().set("userPhone:" +phone,phone);
                return ResData.LOGIN_SUCCESS;
            } else {
                return ResData.CODE_FAIL;
            }

 }

    /*分拣端/配送端用户登录方法，传参手机号，密码*/
    @Override
    public ResData<?> otherUserLogin(String phone, String password) {
        //判断redis里面是否有该用户
        String otherUserPhone = redisTemplate.opsForValue().get("userPhone:" + phone);
        if (otherUserPhone != null){
            return ResData.LOGIN_SUCCESS;
        }
        Users users = usersMapper.otherUserLogin(phone, password);
        //判断查询出来的对象为不为空
        if (users !=null){
            //不为空，把手机号存redis里面，返回登录成功
            redisTemplate.opsForValue().set("userPhone:" +phone,phone);
            return ResData.LOGIN_SUCCESS;
        } else {
            //为空，防止缓存击穿，存一个空的redis
            redisTemplate.opsForValue().set("userPhone:" + phone,"");
            //返回登录失败
            return ResData.LOGIN_FILA;
        }

    }
    /*协作端用户 修改密码 传参，手机号，密码*/
    @Override
    public ResData<?> updatePassword(String phone, String password) {
        usersMapper.updatePassword(phone, password);
        return new ResData<>().ok();
    }

    /*用户退出登录状态*/
    @Override
    public ResData<?> LoginOut() {
       // redisTemplate.delete("userPhone:" +phone);
        return new ResData<>().ok();
    }

    /*后台管理员查询全部的用户信息*/
    @Override
    public ResData<?> queryAllUser(RequestParams<Users> requestParams) {
        PageHelper.startPage(requestParams.getPageNo(),requestParams.getPageSize());
        PageInfo<Users> usersPageInfo = new PageInfo<>(usersMapper.queryAllUser(requestParams.getData().getPhone()));
        return new ResData<>().ok(usersPageInfo);
    }

    /*查询用户端和协作端用户数量*/
    @Override
    public ResData<?> findUsersAndWork() {
        Integer usersAndWork = usersMapper.findUsersAndWork();
        return new ResData<>().ok(usersAndWork);
    }

    /*用户手机号登录*/
    @Override
    public ResData<?> UsersLogin(String phone) {
        String phoneRedis = redisTemplate.opsForValue().get("userPhone:" + phone);
        if (phoneRedis != null){
            return ResData.LOGIN_SUCCESS;
        }
        if (phone != null || ! phone.equals(" ")){
            Users users = usersMapper.UsersLogin(phone);
            if (users != null){
                redisTemplate.opsForValue().set("userPhone:" + phone,"");
                return ResData.LOGIN_SUCCESS;
            }else {
                return ResData.NOT_LOGIN;
            }
        }
       return ResData.LOGIN_FILA;

    }

}
